package inits

import (
	"UserSrv/conf"
	"UserSrv/global/model"
	"UserSrv/global/pkg"
	"encoding/json"
	"fmt"
	"github.com/redis/go-redis/v9"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func Init() {
	conf.GetConf()
	MysqlConn()
	RedisConn()
	go SmsRabbitMQSum()
}

func SmsRabbitMQSum() {
	rabbitmq := pkg.NewRabbitMQSimple("" +
		"SmsSeed")
	msgs := rabbitmq.ConsumeSimple()
	for msg := range msgs {
		var SmsCode pkg.HuYi
		json.Unmarshal(msg.Body, &SmsCode)
		SmsCode.SmsCode()
	}
}

func RedisConn() {
	model.UserRDB = redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%s", conf.Config.Redis.Host, conf.Config.Redis.Port),
		Password: conf.Config.Redis.Password,
		DB:       0,
	})
	if err := model.UserRDB.Set(model.Ctx, "ok", 1, 0).Err(); err != nil {
		panic(err)
	}
	fmt.Println("redis connect success")
}

func MysqlConn() {
	var err error
	model.UserDB, err = gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", conf.Config.Mysql.User, conf.Config.Mysql.Password, conf.Config.Mysql.Host, conf.Config.Mysql.Port, conf.Config.Mysql.Database)))
	if err != nil {
		panic(err)
	}
	if err = model.UserDB.AutoMigrate(&model.User{}); err != nil {
		panic(err)
	}
	fmt.Println("Auto migrate success")
}
